package pl.javarsovia.javarsovia4android.domain;

import android.content.Context;
import pl.javarsovia.javarsovia4android.xml.ConferenceParser;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class ConferenceProvider {

	private static Conference conference;

	public static Conference getConference() {
		return conference;
	}

	public static void readConferenceFromRaw(Context context) throws FileNotFoundException {
		InputStream inputStream = context.openFileInput("conference.xml");
		updateConferenceFromInputStream(inputStream);
	}

	public static void updateConferenceFromWeb(Context ctx) {
		try {
			URL conferenceXmlURL = new URL("http://grzechocinski.net/download/javarsovia/conference.xml");
			URLConnection urlConnection = conferenceXmlURL.openConnection();
			InputStream is = urlConnection.getInputStream();

			OutputStream out = ctx.openFileOutput("conference.xml", Context.MODE_PRIVATE);
			byte buf[] = new byte[1024];
			int len;
			while ((len = is.read(buf)) > 0) {
				out.write(buf, 0, len);
			}
			out.close();
			is.close();

			FileInputStream inputStream = ctx.openFileInput("conference.xml");
			updateConferenceFromInputStream(inputStream);
			inputStream.close();
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage(), e);
		}
	}

	private static void updateConferenceFromInputStream(InputStream inputStream) {
		ConferenceParser parser = new ConferenceParser(inputStream);
		conference = parser.unmarshall();
	}
}
